import { corsHeaders } from './utils/cors.js';

export class Router {
    constructor() {
        this.routes = new Map();
    }

    // 添加路由方法
    addRoute(method, path, handler) {
        const key = `${method}:${path}`;
        this.routes.set(key, handler);
        return this;
    }

    // GET 请求
    get(path, handler) {
        return this.addRoute('GET', path, handler);
    }

    // POST 请求
    post(path, handler) {
        return this.addRoute('POST', path, handler);
    }

    // PUT 请求
    put(path, handler) {
        return this.addRoute('PUT', path, handler);
    }

    // DELETE 请求
    delete(path, handler) {
        return this.addRoute('DELETE', path, handler);
    }

    // 处理请求
    async handle(request, env) {
        // 处理 OPTIONS 请求
        if (request.method === 'OPTIONS') {
            return new Response(null, {
                status: 204,
                headers: corsHeaders
            });
        }

        const url = new URL(request.url);
        const method = request.method;
        const path = url.pathname;

        // 查找精确匹配的路由
        const exactMatch = this.routes.get(`${method}:${path}`);
        if (exactMatch) {
            return await exactMatch(request, env);
        }

        // 查找带参数的路由
        for (const [routeKey, handler] of this.routes) {
            const [routeMethod, routePath] = routeKey.split(':');
            if (routeMethod !== method) continue;

            const match = this.matchRoute(routePath, path);
            if (match) {
                request.params = match;
                return await handler(request, env);
            }
        }

        // 未找到匹配的路由
        return new Response('Not Found', {
            status: 404,
            headers: corsHeaders
        });
    }

    // 匹配带参数的路由
    matchRoute(routePath, actualPath) {
        const routeParts = routePath.split('/');
        const actualParts = actualPath.split('/');

        if (routeParts.length !== actualParts.length) {
            return null;
        }

        const params = {};
        for (let i = 0; i < routeParts.length; i++) {
            const routePart = routeParts[i];
            const actualPart = actualParts[i];

            if (routePart.startsWith(':')) {
                // 这是一个参数
                const paramName = routePart.slice(1);
                params[paramName] = actualPart;
            } else if (routePart !== actualPart) {
                // 不匹配的固定部分
                return null;
            }
        }

        return Object.keys(params).length > 0 ? params : null;
    }
}